<template>
    <div class="app-container">
        <div>
            <!-- <div class="col-body" style="width: 280px;" v-loading="roleLoading">
       
            </div> -->
            <div class="col-body" :style="{ height: HeightTable + 'px', width: 'calc(100% - 0px)' }"
                v-loading="loading">
                <!-- <div class="tree-ad" @click="onButton('move')">
                    <el-button type="primary" :disabled="selectedIds.length == 0">一键移动</el-button>
                </div> -->
                <div class="tree-add">
                    <el-button type="primary" @click="onButton('add')">新增</el-button>
                </div>
                <div class="mx-1" size="large">用户列表</div>
                <div class="blank"></div>
                <div style="display: flex;margin: 10px 0;">
                    <el-input v-model="searchRules.form.blurry" placeholder="请输入用户名称" style="width: 200px;" />
                    <el-button type="primary" @click="searchBtn(1)" style="margin-left: 10px;">搜索</el-button>
                    <el-button @click="searchBtn(0)">重置</el-button>
                </div>
                <el-table :data="tableData" stripe border style="width: 100%" @selection-change="handleSelectionChange"
                    :height="HeightTable - 170">
                    <!-- <el-table-column type="selection" width="55" align="center" /> -->
                    <el-table-column property="id" label="ID" width="120" align="center" />
                    <el-table-column property="username" label=" 用户名" align="center" />
                    <el-table-column property="role" label="权限" align="center" />
                    <el-table-column property="created_at" label="创建时间" align="center" />

                </el-table>
                <el-pagination style="margin-top: 10px;text-align: center;" background
                    layout=" prev, pager, next, total, jumper" :total="tableTotal" :default-page-size="pageSize"
                    :page-sizes="[15, 50, 100]" @current-change="onPageChange" />
            </div>
        </div>
        <el-dialog :visible.sync="addWinShow" :title="addTitle" width="500px" v-loading="addLoading">
            <el-form ref="addForm" :model="addRules.form" :rules="addRules.data" label-width="90px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addRules.form.username" placeholder="请输入用户名" clearable
                        :disabled="addTitle == '查看用户'" />
                </el-form-item>
                <el-form-item label="用户密码" prop="password" v-if="!addRules.form.id">
                    <el-input v-model="addRules.form.password" placeholder="请输入用户密码" clearable
                        :disabled="addTitle == '查看用户'" type="password" />
                </el-form-item>
                <el-form-item label="角色" prop="roleId">
                    <el-select v-model="addRules.form.roleId" placeholder="请选择" style="width: 100%;"
                        :disabled="addTitle == '查看用户'">
                        <el-option :label="item.name" :value="item.value" v-for="item in rolesData" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer v-if="addTitle != '查看用户'">
                <div class="dialog-footer">
                    <el-button @click="addWinShow = false">取消</el-button>
                    <el-button type="primary" @click="onSubmit('addForm')">保存</el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog :visible.sync="addWinShows" title="移动用户" width="400px" draggable>
            <el-form ref="moveForm" :model="addRules.form" label-width="90">
                <el-form-item label="选择组织" prop="deptId">
                    <treeselect v-model="addRules.form.deptId" :options="treeData" clearable placeholder="请选择" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="addWinShows = false">取消</el-button>
                    <el-button type="primary" @click="onSubmit('moveForm')">确定移动</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script>
import { dept, users, all, addUsers, resetPwd, roles, updateUserDept } from '@/api/user.js'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
    components: {
        Treeselect
    },
    data() {
        return {
            loading: false,
            roleLoading: false,
            addLoading: false,
            Height: window.innerHeight - 250,
            HeightTable: window.innerHeight - 90,
            addTitle: '新增用户',
            treeSearch: '',
            treeData: [],
            pageSize: 15,
            tableTotal: 0,
            tableData: [],
            searchRules: {
                form: {
                    blurry: "",
                    phone: "",
                    enabled: '',
                },
                data: {},
            },
            addWinShow: false,
            addWinShows: false,
            rolesData: [{ id: 1, name: '管理员', value: "admin" }, { id: 2, name: '普通用户', value: "user" }],
            selectedIds: [],
            addRules: {
                form: {
                },
                data: {
                    nickName: [
                        {
                            required: true,
                            message: "请输入姓名",
                            trigger: "blur",
                        },
                    ],
                    username: [
                        {
                            required: true,
                            message: "请输入用户名",
                            trigger: "blur",
                        },
                    ],
                    password: [
                        {
                            required: true,
                            message: "请输入密码",
                            trigger: "blur",
                        },
                    ],
                    phone: [
                        {
                            required: true,
                            message: "请输入手机号",
                            trigger: "blur",
                        },
                    ],
                    roleId: [
                        {
                            required: true,
                            message: "请选择角色",
                            trigger: "blur",
                        },
                    ],
                    deptId: [
                        {
                            required: true,
                            message: "请选择部门",
                            trigger: "blur",
                        },
                    ],
                },
            },
        };
    },
    mounted() {
        this.getUserList();
    },
    methods: {
        ontreeSearch(text) {
            this.$refs.myTree.filter(text);
        },
        onTreeFilter(text, data) {
            if (!text) return true;
            return data.label.includes(text);
        },
        onTreeClick(data, node) {
            this.deptId = data.id;
            this.getUserList();
        },
        onButton(type, li) {
            console.log(type)
            let form = {};
            if (li && typeof li.$index != undefined) {
                form = Object.assign({}, this.tableData[li.$index]);
            }
            switch (type) {
                case "add":
                    this.addWinShow = true;
                    this.addRules.form = {
                        policeNo: "",
                        nickName: "",
                        username: "",
                        password: "",
                        phone: "",
                        enabled: true,
                        roleId: "",
                        deptId: null,
                    };
                    this.addTitle = '新增用户'
                    break;

                case "role":
                    this.addWinShow = true;
                    this.addRules.form = form;
                    this.addRules.form.roleId = form.roles[0].id;
                    this.addRules.form.deptId = form.dept.id;
                    this.addTitle = '查看用户'
                    break;
                case "edit":
                    this.addWinShow = true;
                    this.addRules.form = form;
                    this.addRules.form.roleId = form.roles[0].id;
                    this.addRules.form.deptId = form.dept.id;
                    this.addTitle = '编辑用户'
                    break;
                case "move":
                    this.addWinShows = true;

                    if (this.selectedIds.length > 0) {
                        this.addRules.form.deptId = this.deptId;
                    } else {
                        this.addRules.form = form;
                    }
                    break;
                case "enabled":
                    this.loading = true
                    this.updateUser("put", form)
                        .then((res) => {
                            this.$message({
                                message: "切换成功",
                                type: "success",
                            });
                            this.loading = false
                        })
                        .catch((error) => {
                            this.loading = false
                            this.tableData[li.$index][type] = !li.row[type];
                        });
                    break;
                case "resetpwd":
                    this.resetPwd([form.id]).then((res) => {
                        this.$message({
                            message: "密码重置成功",
                            type: "success",
                        });
                    });
                    break;
                case "del":
                    this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        roles([form.id]).then((res) => {
                            this.$message({
                                type: 'success',
                                message: '删除成功'
                            });
                            this.getUserList(1);
                        });
                    }).catch(() => {
                    });



                    break;
            }
        },
        onReset(refname) {
            this.$refs[refname].resetFields();
            this.getUserList(1);
        },
        handleSelectionChange(selectedRows) {
            this.selectedIds = selectedRows.map((row) => row.id);
        },
        searchBtn(type) {
            let form = {};
            if (type == 1) {
                this.getUserList(1, this.searchRules.form.blurry);
            } else {
                this.searchRules.form.blurry = ""
            }

        },
        onSubmit(refname) {
            let form = {};
            this.$refs[refname].validate((valid) => {
                if (valid) {
                    switch (refname) {
                        case "addForm":
                            this.addLoading = true
                            let obj = {
                                username: this.addRules.form.username,
                                password: this.addRules.form.password,
                                role: this.addRules.form.roleId
                            }
                            addUsers(obj).then((res) => {
                                if (res.status == "success") {
                                    this.getUserList(1);
                                    this.$message({
                                        message: res.message,
                                        type: "success",
                                    });
                                    this.addLoading = false
                                } else {
                                    this.$message.error(res.message);
                                    this.addLoading = false
                                }
                            }).catch((err) => {
                                this.addLoading = false
                            })
                            break;
                        case "moveForm":
                            if (this.selectedIds.length > 0) {
                                let f = {
                                    deptId: this.addRules.form.deptId,
                                    ids: this.selectedIds,
                                };
                                updateUserDept(f).then((res) => {
                                    this.$message({
                                        message: "移动成功",
                                        type: "success",
                                    });
                                    this.getUserList(1);
                                })

                                this.addWinShows = false;
                            } else {
                                let f = {
                                    deptId: this.addRules.form.deptId,
                                    ids: [this.addRules.form.id],
                                };
                                updateUserDept(f).then((res) => {
                                    this.$message({
                                        message: "移动成功",
                                        type: "success",
                                    });
                                    this.getUserList(1);
                                })

                                this.addWinShows = false;
                            }

                            break;
                    }
                }
            });
        },
        onPageChange(page) {
            this.getUserList(page);
        },
        getDeptDataById(id) {
            let getById = function (arr, id) {
                for (let i = 0; i < arr.length; i++) {
                    if (arr[i].id === id) {
                        return arr[i];
                    }
                    if (arr[i].hasChildren) {
                        let result = getById(arr[i].children, id);
                        if (result) {
                            return result;
                        }
                    }
                }
                return null;
            };
            if (id) {
                let dept = getById(this.treeData, id);
                return dept ? dept : [];
            } else {
                return [];
            }
        },
        // 获取部门列表
        async getDeptList(pid) {
            pid = pid > 0 ? `pid=${pid}&` : ``;
            let result = await dept(pid)
            return Promise.resolve(result.data.content);
        },
        //获取用户列表
        async getUserList(page, search) {
            page = page ? page : 1;
            search = search ? search : "";
            this.loading = true;
            users(this.pageSize, page, search).then((res) => {
                this.tableData = res.data;
                this.tableTotal = + res.pagination.total_users;
                this.loading = false;
            }).catch((err) => {
                this.loading = false;
            })
        },
        //更新用户信息
        async updateUser(type, form) {
            let result = await addUsers(type, form)
            return Promise.resolve(result.data).catch();
        },
        //重置密码
        async resetPwd(form) {
            let result = resetPwd(form)
            return Promise.resolve(result.data);
        },
    },
};
</script>

<style lang="scss" scoped>
.custom-scrollbar {
    height: calc(100vh - 250px);
    overflow-y: auto;
    scrollbar-width: thin;
    scrollbar-color: #0000 #0000;

    &::-webkit-scrollbar {
        width: 1px;
    }

    &::-webkit-scrollbar-thumb {
        background-color: #0000;
        border-radius: 3px;
    }

    &::-webkit-scrollbar-track {
        background-color: #0000;
    }
}

.col-body .el-input {
    --el-input-width: 220px;
}

.col-body .el-select {
    --el-select-width: 220px;
}

.blank {
    height: 20px;
}

.blank.line {
    height: auto;
    padding-top: 10px;
    margin-bottom: 10px;
    border-bottom: 1px #ebeef5 solid;
}

.col-body {
    position: relative;
    padding: 20px;
    background: #ffffff;
}

.tree-ad {
    position: absolute;
    right: 120px;
}

.tree-add {
    position: absolute;
    right: 20px;
}

.tree-node {
    display: flex;
    align-items: center;
}

.tree-node>span {
    display: block;
}

.tree-node>span:first-child {
    margin-right: 5px;
    font-size: 16px;
}

.tree-node.active {
    color: #409eff;
}

//在全局设置
.app-container ::v-deep input[aria-hidden=true] {
    display: none !important;
}

.app-container ::v-deep .el-dialog {
    margin-top: 5vh !important;
}
</style>